﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Security;
using System.Configuration;
using System.Collections;
using System.Windows.Forms;
using compusUpdates.Properties;

namespace compusUpdates {
    static class Program {

        public static CookieContainer Cookies = new CookieContainer();
        public static List<Lesson> Lessons = new List<Lesson>();
        public static Boolean Connected = new Boolean();

        public static String login() {
            String useragent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.4) Gecko/20091016 Firefox/3.5.4";
            String postdata;
            byte[] data;
            String refer = "http://compus.uom.gr";

            Connected = false;

            //bypass ssl erros
            ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback
                (IgnoreCertificateErrorHandler);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://compus.uom.gr/index.php");
            request.CookieContainer = Cookies;
            request.Method = "POST";
            //request.Credentials = CredentialCache.DefaultCredentials;
            request.UserAgent = useragent;
            request.ContentType = "application/x-www-form-urlencoded";

            try {
                Stream dataStream = request.GetRequestStream();
                dataStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("iso-8859-7"));
                String responseFromServer = reader.ReadToEnd();
                //Console.WriteLine(responseFromServer);

                reader.Close();
                dataStream.Flush();
                dataStream.Close();
                response.Close();

                String formid = findFormId(responseFromServer);
                ///////////////////////////// Second request :)

                postdata = "uname=" + Settings.Default.username + "&pass=" + Settings.Default.password + "&login=%C5%DF%F3%EF%E4%EF%F2&compusFormId=" + formid;
                data = Encoding.Default.GetBytes(postdata);
                request = (HttpWebRequest)WebRequest.Create("https://compus.uom.gr/modules/auth/login.php");

                request.CookieContainer = Cookies;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                request.Referer = refer;
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Headers.Add("Accept-Language", "en-us,en;q=0.5");
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                request.Headers.Add("Keep-Alive", "300");
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;

                //Console.Write(request.Headers.ToString());

                dataStream = request.GetRequestStream();
                dataStream.Write(data, 0, data.Length);
                dataStream.Close();

                response = (HttpWebResponse)request.GetResponse();
                //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                dataStream = response.GetResponseStream();
                reader = new StreamReader(dataStream, Encoding.GetEncoding("iso-8859-7"));
                responseFromServer = reader.ReadToEnd();

                reader.Close();
                dataStream.Flush();
                dataStream.Close();
                response.Close();

                if (!logged(responseFromServer)) {
                    return "";
                } else {
                    Connected = true;
                    return responseFromServer;
                }
            }
            catch (Exception ex) {
                return "";

            }

        }

        private static bool IgnoreCertificateErrorHandler(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) {
            return true;
        }

        public static String findFormId(String html) {
            Match m = Regex.Match(html, "name=\"compusFormId\" value=\"(.*)\"");
            if (m.Success) {
                Console.WriteLine("compusFormId=" + m.Groups[1]);
                return m.Groups[1].Value;
            } else {
                return "error";
            }
        }

        public static void findLessons(String html) {
            Lesson tempLes;
            foreach (Match m in Regex.Matches(html, "a href=\"(.*)/index.php\" title=\"(.*)\"")) {
                tempLes = new Lesson(m.Groups[1].Value.ToString(), m.Groups[2].Value.ToString());
                if (!Lessons.Contains(tempLes)) {
                    Lessons.Add(tempLes);
                }
            }
        }

        public static bool logged(String html) {
            if (Regex.IsMatch(html, "logout")) {
                return true;
            } else {
                return false;
            }
        }

        public static void viewCookies(CookieCollection c) {
            foreach (Cookie cookie in c) {
                Console.WriteLine(cookie.ToString());
            }
        }

        public static void printLessons(IEnumerable List) {
            foreach (Lesson obj in List)
                Console.WriteLine(obj.code + " " + obj.name);
            Console.WriteLine();
        }


        public static void RunStartup() {
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (Settings.Default.startup) {
                key.SetValue("Compus", Application.ExecutablePath.ToString());
            } else {
                key.DeleteValue("Compus");
            }
        }



        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormTray());

        }
    }
}
